package com.shop.common.partner.nameauth;

import com.alibaba.fastjson.JSON;
import com.shop.util.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class RealNameAuthImpl implements IRealNameAuth {

    private static final String HOST = "http://idcert.market.alicloudapi.com";
    private static final String PATH = "/idcard";
    private static final String appcode = "3def4aa1fef64e1395e4a058f6a8727b";

    @Override
    public boolean auth(String realName, String idNumber) {

        RealNameAuthentication realNameAuthentication = null;
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appcode);

        //拼接url
        StringBuilder url = new StringBuilder();
        url.append(HOST).append(PATH).append("?idCard=").append(idNumber).append("&").append("name=").append(realName);

        try {
            Map response = HttpUtil.get(url.toString(), headers);
            //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
            //获取response的body
            if (response.get("body") != null) {
                realNameAuthentication = JSON.parseObject(response.get("body").toString(), RealNameAuthentication.class);
                String status = realNameAuthentication.getStatus();
                if("01".equals(status) || "202".equals(status)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("实名认证异常", e);
            return false;
        }

        return false;
    }

}
